<?php

namespace App\Http\Controllers\Api\Teacher;

use App\Models\Question;
use App\Models\QuestionsCategory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class QuestionBankController extends Controller
{
    /**
     * 题库列表（带分类关联和搜索）
     * GET /api/teacher/questions
     */
    public function index(Request $request)
    {
        // 请求参数
        $content = $request->input('content'); // 题目内容搜索
        $categoryId = $request->input('category_id'); // 分类筛选
        $type = $request->input('type'); // 题型筛选（1单选/2多选/3判断）
        $status = $request->input('status', 1);
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 10);

        $query = Question::with('category:id,name'); // 关联分类信息

        // 搜索条件
        if (!empty($content)) {
            $query->where('content', 'like', "%{$content}%");
        }
        if (!empty($categoryId)) {
            $query->where('category_id', $categoryId);
        }
        if (isset($type)) {
            $query->where('type', $type);
        }
        if (isset($status)) {
            $query->where('status', $status);
        }

        // 分页查询
        $questions = $query->paginate($pageSize, ['*'], 'page', $page);

        return $this->paginated($questions->items(), $questions);
    }

    /**
     * 题库分类列表（带搜索）
     * GET /api/teacher/questions-categories
     */
    public function categoryList(Request $request)
    {
        $name = $request->input('name'); // 分类名称搜索
        $query = QuestionsCategory::where('status', 1); // 只显示正常分类

        if (!empty($name)) {
            $query->where('name', 'like', "%{$name}%");
        }

        $categories = $query->get();
        return $this->success($categories);
    }

    /**
     * 新增/编辑题目
     * POST/PUT /api/teacher/questions
     */
    public function save(Request $request)
    {
        // 验证参数
        $validated = $request->validate([
            'id' => 'nullable|integer|exists:questions,id', // 编辑时必传
            'category_id' => 'nullable|integer|exists:knowledge_categories,id',
            'category' => 'required_if:category_id,null|string|max:50',
            'content' => 'required|string', // 题目内容
            'type' => 'required|in:1,2,3', // 1单选/2多选/3判断
            'options' => 'required_if:type,1,2|array', // 单选/多选必须有选项
            'answer' => 'required|string', // 答案（单选/判断：单个值；多选：逗号分隔）
            'explanation' => 'nullable|string', // 解析
            'status' => 'boolean'
        ]);

        // 处理分类逻辑
        $categoryId = $request->input('category_id');
        if (empty($categoryId)) {
            // 如果category_id为空，则创建新分类
            $category = QuestionsCategory::create([
                'name' => $request->input('category'),
                'status' => 1
            ]);
            $validated['category_id'] = $category->id;
        } else {
            // 如果category_id不为空，则使用传入的category_id
            $validated['category_id'] = $categoryId;
        }

        // 添加当前教师ID
        $validated['teacher_id'] = auth('admin')->id();

        // 处理选项（转为JSON字符串存储）
        if (isset($validated['options'])) {
            $validated['options'] = json_encode($validated['options']);
        }

        // 新增或更新题目
        $question = Question::updateOrCreate(
            ['id' => $request->input('id')],
            $validated
        );

        // 关联分类信息返回
        $question->load('category:id,name');

        $message = $request->input('id') ? '题目更新成功' : '题目创建成功';
        return $this->success($question, $message);
    }
}
